{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "https://mp.weixin.qq.com/s?__biz=MzkxODE3NjExOQ==&mid=2247485406&idx=1&sn=c86294e744922b2674e573cf9b2ee63f&chksm=c1b42fc6f6c3a6d0c7400d0df5669eba03dd8c8516347345fa60bd8f6f69e45685fd8faa1e07&scene=178&cur_album_id=3354758663365918722#rd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 导入需要使用的库\n",
    "import akshare as ak\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "# 关闭警告信息\n",
    "import warnings\n",
    "warnings.filterwarnings('ignore')\n",
    "\n",
    "# 获取沪深300指数10年的收盘价数据\n",
    "start_date = '20140101'  # 开始日期\n",
    "end_date = '20231229'  # 结束日期\n",
    "bars = ak.stock_zh_index_hist_csindex(symbol='000300', start_date=start_date, end_date=end_date)\n",
    "price_df = bars[['日期','收盘']]\n",
    "# 将日期设置为datetime格式\n",
    "price_df['日期'] = pd.to_datetime(price_df['日期'])\n",
    "price_df.set_index('日期', inplace=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.013863580586810233 0.028494415455448247 0.06256091415370335\n"
     ]
    }
   ],
   "source": [
    "# 用日收益率计算波动率\n",
    "daily_return = price_df['收盘'].pct_change()  # 日收益率\n",
    "vol_1 = daily_return.std()\n",
    "\n",
    "# 用周收益率计算波动率\n",
    "weekly_return = (1 + daily_return).resample('W').prod() - 1  # 周收益率\n",
    "vol_2 = weekly_return.std()\n",
    "\n",
    "# 用月收益率计算波动率\n",
    "monthly_return = (1 + daily_return).resample('M').prod() - 1  # 月收益率\n",
    "vol_3 = monthly_return.std()\n",
    "\n",
    "print(vol_1,vol_2,vol_3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.2165560515700808 0.20547615197798447 0.21671736376433817\n"
     ]
    }
   ],
   "source": [
    "# 计算年化的波动率\n",
    "vol_1 = daily_return.std() * np.sqrt(244)\n",
    "vol_2 = weekly_return.std() * np.sqrt(52)\n",
    "vol_3 = monthly_return.std() * np.sqrt(12)\n",
    "print(vol_1,vol_2,vol_3)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "4broker",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
